/**
 * create by young (young2f@outlook.com) on 2023/4/28
 */
'use strict';
const fs = require('fs');
const pointArr = fs.readFileSync('./point.json', 'utf8');
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {

    if (this.readyState == 4 && this.status == 200) {
        console.log(req.responseText);
        const res = JSON.parse(req.responseText);
        const {result} = res;
        const {devices} = result;

        devices.forEach(device => {
            sendData(device);
        });

    }
};
req.open('POST', 'http://127.0.0.1:18008/api/device/find/page', true);

req.setRequestHeader('Content-Type', 'application/json;charset=utf-8');

req.send(JSON.stringify({tenantCode: 'TEN23042822280074F9', skip: 1, limit: 200}));

// }
function rand(min, max) {
    return Math.ceil(Math.random() * (max - min + 1) + min - 1);
}

function getNomData(device) {
    const {name, type, len} = device;
    switch (type) {
        case 'bool':
            return rand(0, 1);
        case 'uni16':
            return rand(0, Math.pow(10,len));
        default :
            return Math.floor(Math.random() * 9);
    }
}

function sendData(device) {
    console.log('device', device);
    const {points,deviceCode,deviceSpecCode,tenantCode} = device;

    const params = [];
    points.forEach(item => {
        const {name, path} = item;
        params.push({name, path, value: getNomData(item)});
    });
    device.params = params;
    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    var req = new XMLHttpRequest();
    req.onreadystatechange = function () {
        console.log(this.status);
        if (this.readyState == 4 && this.status == 200) {
            console.log('上报数据', req.responseText);
        }
    };
    req.open('POST', 'http://127.0.0.1:18008/api/device/data/create', true);

    req.setRequestHeader('Content-Type', 'application/json;charset=utf-8');

    req.send(JSON.stringify({deviceCode,deviceSpecCode,tenantCode,params}));
}
